Ext.ns('ru.proburo.oms.order.components.form');

/**
 * @class ru.proburo.oms.order.components.form.Panel
 * @extends Ext.FormPanel
 */
ru.proburo.oms.order.components.form.Panel = Ext.extend(Ext.FormPanel, {
    
	_lastDirty: false,
	_lastValid: true,
    
	constructor: function(config)
	{
		config = config || {};
		
		this.record = config.record;
		
        Ext.applyIf(config, {			
            defaults:
			{
                width:      500,
                allowBlank: false
            },		
			
            maskDisabled:     false,
			monitorValid:     true,
            trackResetOnLoad: true,
            
            items: this.initFields()
		});
        
        ru.proburo.oms.order.components.form.Panel.superclass.constructor.call(this, config);
		
		this.getForm().loadRecord(this.record);
	},
	
	initEvents: function()
	{
		ru.proburo.oms.order.components.form.Panel.superclass.initEvents.call(this);
		
		this.addEvents({
            'save':   true,
			'change': true
        });
		
		this.on({
			'clientvalidation': this._onClientValidation,
			scope: this
		});
	},
    
    initFields: function()
    {
		if(Ext.isAir)
		{
			return [
				{
					xtype: 'hidden',
					name: 'status'
				},
				
				// all versions
				{
					xtype: 'textfield',
					fieldLabel: 'Адрес доставки',
					name: 'address'
				},
				{
					xtype: 'textfield',
					fieldLabel: 'Контактное лицо',
					name: 'contact_person'
				},
				{
					xtype: 'textfield',
					fieldLabel: 'Телефон',
					name: 'phone'
				},
				{
					xtype: 'textarea',
					fieldLabel: 'Комментарии',
					name: 'comments',
					allowBlank: true
				}
			];
		}
		else
		{
			var customer   = {
				id:   this.record.get('customer_id'),
				name: this.record.get('customer')
			};
			var department = {
				id:   this.record.get('department_id'),
				name: this.record.get('department')
			};
			
			
			
			var dCombo = new Ext.form.ComboBox({
				store: new ru.proburo.oms.dao.JsonStore({
					url: 	'/services/department/list.json',
					fields: ['id', 'name']
				}),
				
				id:			  'department_id',
				name: 		  'department_id',
				fieldLabel:   'Подразделение',
				valueField:   'id',
				displayField: 'name',
				emptyText: 	  'Выберите подразделение...',
				
				mode: 		   'remote',
				editable: 	   false,
				triggerAction: 'all'
			});
			dCombo.getStore().loadData({items: [department]});
			
			
			
			var cCombo = new ru.proburo.oms.components.form.FilterableComboBox({
				store: new ru.proburo.oms.dao.JsonStore({
					url: 	'/services/customer/list.json',
					fields: ['id', 'name', 'sales_direction', 'warehouse']
				}),
				
				id:			  'customer_id',
				name: 		  'customer_id',
				fieldLabel:   'Юр. лицо',
				valueField:   'id',
				displayField: 'name',
				emptyText: 	  'Выберите юр. лицо...',
				editable: 	  false,
				
				//HCombo conf
				masterField:  dCombo,
				filterField:  'department_id',
				relayClear:   true
			});
			cCombo.getStore().setBaseParam('department_id', department.id);
			cCombo.getStore().loadData({items: [customer]});
			
			
			
			var aCombo = new ru.proburo.oms.components.form.FilterableComboBox({
				store: new ru.proburo.oms.dao.JsonStore({
					url: 	'/services/customer/address/list.json',
					fields: ['id', 'address']
				}),
				
				name: 		  'address',
				fieldLabel:   'Адрес доставки',
				valueField:   'id',
				displayField: 'address',
				emptyText:    'Выберите адрес доставки...',
				editable: 	  true,
				
				//HCombo conf
				masterField:  cCombo,
				filterField:  'customer_id',
				relayClear:   false
			});
			aCombo.getStore().setBaseParam('customer_id', customer.id);
			
			
			
			return [
				// only for online version
				{
					xtype: 'hidden',
					name:  'status'
				},
				{
					xtype: 'hidden',
					name:  'delivery_date'
				},
				dCombo,				
				cCombo,
				
				// all versions
				aCombo,
				{
					xtype: 		'textfield',
					fieldLabel: 'Контактное лицо',
					name: 		'contact_person'
				},
				{
					xtype: 		'textfield',
					fieldLabel: 'Телефон',
					name: 		'phone'
				},
				{
					xtype: 		'textarea',
					fieldLabel: 'Комментарии',
					name: 		'comments',
					allowBlank: true
				}
			];
		}
    },
	
	isDirty: function(){
		return this.getForm().isDirty();
	},
	
	isValid: function(){
		return this.getForm().isValid();
	},
	
	save: function(callback, scope)
	{
        if(callback)
		{
            this.on('save', callback, scope, {single:true});
        }
		
		var form = this.getForm();
		
		form.updateRecord(this.record);
		
		var r = this.record;
		
		if(this.record.store)
		{
			var getDisplayValue = function(combo)
			{
				if(combo)
				{
					var record = combo.findRecord(combo.valueField, combo.getValue());
					
					if(record)
					{
						return record.data[combo.displayField];
					}
				}
				
				return '';
			};
			
			if(!Ext.isAir)
			{
				var dCombo = this.getForm().findField('department_id');
				this.record.set('department', getDisplayValue(dCombo));
				
				var cCombo = this.getForm().findField('customer_id');
				this.record.set('customer', getDisplayValue(cCombo));
			}
			
			this.record.set('modified_date', new Date());
			
			this.record.store.on('save', this._onStoreSave, this, {single: true});
			this.record.store.saveRecord(this.record);
		}
		
		this.record = r;
		
		form.loadRecord(this.record);
	},
	
	/**
	 * Listeners
	 */
	
	// private
	_onStoreSave: function(store, batch, data)
	{
		this.fireEvent('save', this);
	},
	
	// private
	_onClientValidation: function(form, valid)
	{
		var dirty = form.isDirty();
		
		if(dirty != this._lastDirty || valid != this._lastValid)
		{
			this._lastDirty = dirty;
			this._lastValid = valid;
			
			this.fireEvent('change', this);
		}
	}
});